package com.COMP3111H.project;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

public class SellLend_Confirm extends Activity {
	final int HELP = 0;
	Button menu;
	ProgressThread progThread;
	final int SPINNER = 0;
	ProgressDialog progDialog;
	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.selllend_confirm);
		menu = (Button) findViewById(R.id.SellLend_Confirm_menu);

		final Bundle extras = getIntent().getExtras();
		TextView tv_title = (TextView) findViewById(R.id.sell_confirm_book_title);
		TextView tv_edition = (TextView) findViewById(R.id.sell_confirm_edition);
		TextView tv_courses = (TextView) findViewById(R.id.sell_confirm_courses);
		TextView tv_authors = (TextView) findViewById(R.id.sell_confirm_authors);
		TextView tv_publishers = (TextView) findViewById(R.id.sell_confirm_publishers);
		TextView tv_ISBN = (TextView) findViewById(R.id.sell_confirm_isbn);
		tv_title.setText(extras.getString("title"));
		tv_edition.setText(extras.getString("edition"));
		tv_courses.setText(extras.getString("courses"));
		tv_authors.setText(extras.getString("authors"));
		tv_publishers.setText(extras.getString("publishers"));
		tv_ISBN.setText(extras.getString("ISBN"));
		
		int conditionPos = 1;			// used for condition spinner
		int selllendPos = 0;			// used for sell/lend spinner
		
		final EditText editprice = (EditText) findViewById(R.id.confirm_sl_price);
		final EditText editedition = (EditText) findViewById(R.id.sl_confirm_edit_edition);
		final EditText editisbn = (EditText) findViewById(R.id.sl_confirm_edit_isbn);
        
		// configure condition spinner
        final Spinner c_spinner = (Spinner) findViewById(R.id.confirm_condition_spinner);
        ArrayAdapter<CharSequence> c_adapter = ArrayAdapter.createFromResource(this, R.array.condition_array, android.R.layout.simple_spinner_item);
        c_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        c_spinner.setAdapter(c_adapter);
        c_spinner.setSelection(conditionPos);
        
        // configure sell/lend spinner
        final Spinner sl_spinner = (Spinner) findViewById(R.id.confirm_selllend_spinner);
        ArrayAdapter<CharSequence> sl_adapter = ArrayAdapter.createFromResource(this, R.array.selllend_array, android.R.layout.simple_spinner_item);
        sl_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        sl_spinner.setAdapter(sl_adapter);
        sl_spinner.setSelection(selllendPos);
        sl_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){
    		TableRow price = (TableRow) findViewById(R.id.confirm_price_row);

    		public void onItemSelected(AdapterView<?> parent, View view, int pos,
    				long id) {
    			//Toast.makeText(parent.getContext(),parent.getItemAtPosition(pos).toString() + " is selected",Toast.LENGTH_LONG).show();
    			if (pos == 1) {
    				price.setVisibility(View.GONE);
    			}
    			if (pos == 0) {
    				price.setVisibility(View.VISIBLE);
    			}
    		}

    		public void onNothingSelected(AdapterView<?> parent) { // Do nothing.
    		}
        });
   
        // handles *CHANGE EDITION* functionality
		final Button change = (Button) findViewById(R.id.sl_confirm_change);
		final EditText edittext = (EditText) findViewById(R.id.sl_confirm_edit_edition);
		final TableRow isbn = (TableRow) findViewById(R.id.sl_confirm_edition);
		final Button cancel_change = (Button)findViewById(R.id.sl_confirm_cancel_change);
		change.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				change.setVisibility(View.GONE);
				edittext.setVisibility(View.VISIBLE);
				isbn.setVisibility(View.VISIBLE);
				cancel_change.setVisibility(View.VISIBLE);
			}
		});
		
		cancel_change.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				change.setVisibility(View.VISIBLE);
				edittext.setVisibility(View.GONE);
				isbn.setVisibility(View.GONE);
				cancel_change.setVisibility(View.GONE);
			}
		});
		
		
		if (extras.getBoolean("modify")) {
			findViewById(R.id.edition_change).setVisibility(View.GONE);
			String type = extras.getString("type");
			String condition = extras.getString("condition");
			if (condition.contains("New")) {
				c_spinner.setSelection(0);
			} else if (condition.contains("Good")) {
				c_spinner.setSelection(1);
			} else if (condition.contains("Fair")) {
				c_spinner.setSelection(2);
			}

			if (type.contains("sell")) {
				sl_spinner.setSelection(0);
				editprice.setText(extras.getString("price"));
			} else if (type.contains("lend")) {
				sl_spinner.setSelection(1);
				((TableRow) findViewById(R.id.confirm_price_row))
						.setVisibility(View.GONE);
			} else if (type.contains("resell")) {
				sl_spinner.setSelection(0);
				editprice.setText(extras.getString("price"));
			}
		}
        
		// configure *CONTINUE* and *CANCEL* buttons
		Button cancel = (Button) findViewById(R.id.sl_confirm_cancel);
		Button cont = (Button) findViewById(R.id.sl_confirm_cont);
		cont.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				if(!LoginUtility.checkLoginStatus(SellLend_Confirm.this)){
					Intent i = new Intent(SellLend_Confirm.this,
							Login.class);
					startActivity(i);
					return;
				}
				
				String priceString = editprice.getText().toString();
				String isbnString = editisbn.getText().toString();
				String editionString = editedition.getText().toString();
				
				
				if (priceString.matches("") && sl_spinner.getSelectedItemPosition()==0){
						Toast.makeText(SellLend_Confirm.this,"Please input price", Toast.LENGTH_SHORT).show();
				}
				else if(sl_spinner.getSelectedItemPosition() == 1){
					Log.v("Bookwarm", "lend");
					if(extras.getBoolean("modify")){
						Log.v("Bookwarm", "Modify lend");
						List<NameValuePair> params = new ArrayList<NameValuePair>(3);
	            		params.add(new BasicNameValuePair("copyid", extras.getString("copyid")));
	            		params.add(new BasicNameValuePair("username", LoginUtility.getUsernamePassword(SellLend_Confirm.this)[0]));
	            		params.add(new BasicNameValuePair("copycondition", c_spinner.getItemAtPosition(c_spinner.getSelectedItemPosition()).toString()));
	            		Log.v("Bookwarm", extras.getString("copyid") + "," + LoginUtility.getUsernamePassword(SellLend_Confirm.this)[0] + "," +  c_spinner.getItemAtPosition(c_spinner.getSelectedItemPosition()).toString());
	            		
	            		if(extras.getString("type").contains("buy-resell")){
							//TODO
	            			showDialog(SPINNER);
	            			progThread = new ProgressThread(mhandler,params, 0);
	            			progThread.start();
	            		}
						else{
							showDialog(SPINNER);
	            			progThread = new ProgressThread(mhandler,params, 1);
	            			progThread.start();
						}
					}
					else{
						Intent myIntent = new Intent(SellLend_Confirm.this,
								Agreement.class);
						myIntent.putExtra("origin", 2);
						myIntent.putExtra("isbn",extras.getString("ISBN"));
						myIntent.putExtra("condition", c_spinner.getItemAtPosition(c_spinner.getSelectedItemPosition()).toString());
						if((isbnString.matches("")) && (editionString.matches("")))
							myIntent.putExtra("changeEdition", false);
						else
						{
							if(editionString.equals(extras.getString("edition"))){
								Toast.makeText(SellLend_Confirm.this,"The new edition is the same as the old one. Please change!", Toast.LENGTH_LONG).show();
								return;
							}else{
								myIntent.putExtra("changeEdition", true);
								myIntent.putExtra("newEdition", editionString);
								myIntent.putExtra("newisbn", isbnString);
							}
						}
						startActivity(myIntent);
					}
				}
				else if(sl_spinner.getSelectedItemPosition()==0)
				{	
					if(extras.getBoolean("modify")){
						Log.v("Bookwarm", "To Sell");
						List<NameValuePair> params = new ArrayList<NameValuePair>(4);
	            		params.add(new BasicNameValuePair("copyid", extras.getString("copyid")));
	            		params.add(new BasicNameValuePair("username", LoginUtility.getUsernamePassword(SellLend_Confirm.this)[0]));
	            		params.add(new BasicNameValuePair("copycondition", c_spinner.getItemAtPosition(c_spinner.getSelectedItemPosition()).toString()));
	            		params.add(new BasicNameValuePair("copyprice", priceString));
	            		
	            		if(extras.getString("type").contains("buy-resell")){
							//TODO
	            			showDialog(SPINNER);
	            			progThread = new ProgressThread(mhandler,params, 2);
	            			progThread.start();
						}
						else{
							showDialog(SPINNER);
							progThread = new ProgressThread(mhandler,params, 3);
							progThread.start();	
						}	
					}
					else{
						Intent myIntent = new Intent(SellLend_Confirm.this,
								Agreement.class);
						myIntent.putExtra("origin", 0);						// indicates the origin to be *SELL*
						myIntent.putExtra("isbn",extras.getString("ISBN"));
						myIntent.putExtra("price", priceString);
						myIntent.putExtra("condition", c_spinner.getItemAtPosition(c_spinner.getSelectedItemPosition()).toString());
						myIntent.putExtra("selllend", sl_spinner.getSelectedItemPosition());
						
						if(change.getVisibility()==View.VISIBLE){			// checks if the user intends to change edition (if so, *CHANGE* button should be GONE)
							myIntent.putExtra("changeEdition", false);
							startActivity(myIntent);
						}	
						else if (isbnString.matches(""))					
							Toast.makeText(SellLend_Confirm.this,"Please input ISBN", Toast.LENGTH_SHORT).show();
						else if (editionString.matches(""))					
							Toast.makeText(SellLend_Confirm.this,"Please input edition", Toast.LENGTH_SHORT).show();
						else
						{
							if(editionString.equals(extras.getString("edition"))){
								Toast.makeText(SellLend_Confirm.this,"The new edition is the same as the old one. Please change!", Toast.LENGTH_LONG).show();
								return;
							}else{
								myIntent.putExtra("changeEdition", true);
								myIntent.putExtra("newEdition", editionString);
								myIntent.putExtra("newisbn", isbnString);
								startActivity(myIntent);
							}
						}	
					}
				}
			}
		});
		
		cancel.setOnClickListener(new View.OnClickListener() {			

			public void onClick(View v) {
				finish();
			}
		});

		Button more_info_c = (Button) findViewById(R.id.confirm_c_more_info);
		Button more_info_sl = (Button) findViewById(R.id.confirm_sl_more_info);
		more_info_c.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				Intent myIntent = new Intent(SellLend_Confirm.this,
						More_InfoBook_Condition.class);
				startActivity(myIntent);
			}
		});
		more_info_sl.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				Intent myIntent = new Intent(SellLend_Confirm.this, More_InfoCredit.class);
				startActivity(myIntent);
			}
		});
		
	}
	
	@Override
    protected void onResume() {
		super.onResume();
		if (LoginUtility.checkLoginStatus(this)) {
			menu.setOnClickListener(new View.OnClickListener() {
				public void onClick(View v) {
					 String[] choices={"Home","View My Profile","Help","Cancel"};  
					             AlertDialog dialog = new AlertDialog.Builder(SellLend_Confirm.this)  
					                     // .setIcon(android.R.drawable.btn_star)  
					                      .setTitle("Menu")  
					                      .setItems(choices, onselect_logged).create();  
					             dialog.show();  
				}
			});
		}
		else{
			menu.setOnClickListener(new View.OnClickListener() {
				public void onClick(View v) {
					 String[] choices={"Home","Help","Cancel"};  
					             AlertDialog dialog = new AlertDialog.Builder(SellLend_Confirm.this)  
					                     // .setIcon(android.R.drawable.btn_star)  
					                      .setTitle("Menu")  
					                      .setItems(choices, onselect_not_logged).create();  
					             dialog.show();  
				}
			});
		}
	}

	OnClickListener onselect_logged = new OnClickListener() {
		public void onClick(DialogInterface dialog, int which) {
			// TODO Auto-generated method stub
			Intent myIntent;
			switch (which) {
			case 0:
				myIntent = new Intent(SellLend_Confirm.this, Home.class);
				startActivity(myIntent);
				break;
			case 1:
				myIntent = new Intent(SellLend_Confirm.this, My_Profile.class);
				startActivity(myIntent);
				break;
			case 2:
				myIntent = new Intent(SellLend_Confirm.this, Help.class);
				startActivity(myIntent);
				break;
			case 3:
				dialog.dismiss();
				break;
			}
		}
	};
	
	OnClickListener onselect_not_logged = new OnClickListener() {
		public void onClick(DialogInterface dialog, int which) {
			// TODO Auto-generated method stub
			Intent myIntent;
			switch (which) {
			case 0:
				myIntent = new Intent(SellLend_Confirm.this, Home.class);
				startActivity(myIntent);
				break;
			case 1:
				myIntent = new Intent(SellLend_Confirm.this, Help.class);
				startActivity(myIntent);
				break;
			case 2:
				dialog.dismiss();
				break;
			}
		}
	};
	
	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case 0: // Spinner
			progDialog = new ProgressDialog(this);
			progDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			progDialog.setMessage("Loading...");

			return progDialog;
		default:
			return null;
		}
	}

	// Handler on the main (UI) thread that will receive messages from the
	// second thread and update the progress.

	final Handler mhandler = new Handler() {
		public void handleMessage(Message msg) {
			// Get the current value of the variable total from the message data
			// and update the progress bar.
			String returnedData = msg.getData().getString("returnedData");
			removeDialog(SPINNER);		
			int from = msg.getData().getInt("from");
			if(from == 0 || from == 1){
				if(returnedData.contains("user_not_logged_in")){
					Toast.makeText(SellLend_Confirm.this,"Not Logged In", Toast.LENGTH_LONG).show();
				}
				else if(returnedData.contains("modify_to_lend_successful")){
					Toast.makeText(SellLend_Confirm.this,"Modification of transaction is successful", Toast.LENGTH_SHORT).show();
					Intent myIntent = new Intent(SellLend_Confirm.this, My_Profile.class);
                	startActivity(myIntent);  
				}
				else if(returnedData.contains("modify_to_lend_failed"))
					Toast.makeText(SellLend_Confirm.this,"Modification Failed", Toast.LENGTH_LONG).show();
				else
					Toast.makeText(SellLend_Confirm.this,"Network Error", Toast.LENGTH_LONG).show();
			}
			else if(from == 2 || from == 3){
				if(returnedData.contains("user_not_logged_in")){
					Toast.makeText(SellLend_Confirm.this,"Not Logged In", Toast.LENGTH_LONG).show();
				}
				else if(returnedData.contains("modify_to_sell_successful")){
					Toast.makeText(SellLend_Confirm.this,"Modification of transaction is successful", Toast.LENGTH_SHORT).show();
					Intent myIntent = new Intent(SellLend_Confirm.this, My_Profile.class);
                	startActivity(myIntent);  
				}
				else if(returnedData.contains("modify_to_sell_failed")){
					Toast.makeText(SellLend_Confirm.this,"Modification Failed", Toast.LENGTH_LONG).show();
				}
				else if(returnedData.contains("insufficient_credit"))
					Toast.makeText(SellLend_Confirm.this,"You have used up all your credits. Making this change would make your credit negative.", Toast.LENGTH_SHORT).show();
				else
					Toast.makeText(SellLend_Confirm.this,"Network Error", Toast.LENGTH_LONG).show();
			}
		}
	};

	private class ProgressThread extends Thread {
		// Class constants defining state of the thread
		Handler mHandler;
		List<NameValuePair> params;
		int from;

		ProgressThread(Handler h,List<NameValuePair> p, int f) {
			mHandler = h;
			params = p;
			from = f;
		}

		@Override
		public void run() {
			Message msg = mHandler.obtainMessage();
			String returnedData;
			if(from == 0){
				returnedData = NetworkUtility.sendHTTP(params,"http://webproject2.cse.ust.hk:8029/BookwarmMobile/jsp/buy_borrow_history_list_to_lend.jsp");
				
				Bundle b = new Bundle();
				b.putString("returnedData", returnedData);
				b.putInt("from", from);
				msg.setData(b);
				mHandler.sendMessage(msg);
			}
			else if(from == 1){
				returnedData = NetworkUtility.sendHTTP(params,"http://webproject2.cse.ust.hk:8029/BookwarmMobile/jsp/sell_lend_history_modify_to_lend.jsp");
				Bundle b = new Bundle();
				b.putString("returnedData", returnedData);
				b.putInt("from", from);
				msg.setData(b);
				mHandler.sendMessage(msg);
			}
			else if(from == 2){
				returnedData = NetworkUtility.sendHTTP(params,"http://webproject2.cse.ust.hk:8029/BookwarmMobile/jsp/buy_borrow_history_list_to_sell.jsp");
				Bundle b = new Bundle();
				b.putString("returnedData", returnedData);
				b.putInt("from", from);
				msg.setData(b);
				mHandler.sendMessage(msg);
			}
			else if(from == 3){
				returnedData = NetworkUtility.sendHTTP(params,"http://webproject2.cse.ust.hk:8029/BookwarmMobile/jsp/sell_lend_history_modify_to_sell.jsp");
				Bundle b = new Bundle();
				b.putString("returnedData", returnedData);
				b.putInt("from", from);
				msg.setData(b);
				mHandler.sendMessage(msg);
			}
		
		}

		// Set current state of thread (use state=ProgressThread.DONE to stop
		// thread)

	}

}
